//
//  EmoticonTextView.swift
//  KeyBoard
//
//  Created by mac on 15/12/27.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

class EmoticonTextView: UITextView {

    func insertEmoticon(em:Emoticons) {
        if em.isEmpty {
            return
        }
        if em.isDelete {
            //删除一个文字
            deleteBackward()
            return
        }
        if em.code != nil {
            replaceRange(selectedTextRange!, withText: em.codeStr ?? "")
            return
        }
        let imageText = EmoticonTextAttachment().imageTextToText(em, font: font!)
        
        //记录替换文本的位置
        let range = selectedRange
        //讲属性文本进行替换
        let strM = NSMutableAttributedString(attributedString: attributedText)
        strM.replaceCharactersInRange(range, withAttributedString: imageText)
        attributedText = strM
        selectedRange = NSMakeRange(range.location + 1, 0)
        //主动改变展位文本
        delegate?.textViewDidChange?(self)
    }
    
    
    func imageTextViewToText() -> String {
        //讲属性文本转换为字符串文本
        let attrText = attributedText
        var strM = String()
        //遍历字符串进行替换
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: []) { (dict, Range, _) -> Void in
            //            print(dict)
            //            print("----------")
            //            print(Range)
            if let attachment = dict["NSAttachment"] as? EmoticonTextAttachment{
                //有图片
                strM += attachment.chs ?? ""
            } else {
                let str = (self.text as NSString).substringWithRange(Range)
                strM += str
            }
        }
        return strM
    }

}
